package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.template.AliyunOssTemplate;
import com.tanhua.commons.template.BaiduAipFaceTemplate;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.CommonLikeUser;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private SettingsApi settingsApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private BlackListApi blackListApi;
    @Reference
    private UserApi userApi;
    @Reference
    private FriendApi friendApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Autowired
    private AliyunOssTemplate ossTemplate;
    @Autowired
    private BaiduAipFaceTemplate aipFaceTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;


    public ResponseEntity findUserInfo(long id) {
        UserInfo userinfo = userInfoApi.findById(id);
        UserInfoVO vo = new UserInfoVO();

        BeanUtils.copyProperties(userinfo, vo);
        if (userinfo.getAge() != null) {
            vo.setAge(String.valueOf(userinfo.getAge()));
        }
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo) {
        User user = UserHolder.getUser();
        //2. 把user的id设置到userInfo对象
        userInfo.setId(user.getId());
        //3. 把userInfo更新到数据库
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity updateHeadPhoto(MultipartFile headPhoto) throws IOException {
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceDetectFailed());
        }

        String path = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        UserInfo userInfo = new UserInfo();
        userInfo.setId(UserHolder.getUser().getId());
        userInfo.setAvatar(path);

        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findSettings() {

        User user = UserHolder.getUser();
        //
        Question question = questionApi.findByUserId(user.getId());

        Settings settings = settingsApi.findByUserId(user.getId());

        SettingsVO vo = new SettingsVO();
        if (question != null) {
            vo.setStrangerQuestion(question.getTxt());
        }
        if (settings != null) {
            //如果查询到了通知设置，加载这些设置
            BeanUtils.copyProperties(settings, vo);
        } else {
            //如果没有查询到通知设置，就给默认值
            vo.setLikeNotification(true);
            vo.setGonggaoNotification(true);
            vo.setPinglunNotification(true);
        }
        //4.3 设置手机号
        vo.setPhone(user.getMobile());
        vo.setId(user.getId());

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateQuestion(String questionTxt) {
        //获取当前对象
        User user = UserHolder.getUser();
        Question question = questionApi.findByUserId(user.getId());
        if (question != null) {
            question.setTxt(questionTxt);
            questionApi.updata(question);
        } else {
            question = new Question();
            question.setUserId(user.getId());
            question.setTxt(questionTxt);
            questionApi.save(question);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveSettings(Settings settings) {
        Long userId = UserHolder.getUser().getId();
        Settings userSettings = settingsApi.findByUserId(userId);
        if (userSettings == null) {
            settings.setUserId(userId);
            settingsApi.save(settings);

        } else {
            //查询到了通知设置，则修改设置
            settings.setId(userSettings.getId());
            settingsApi.update(settings);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findBlackList(int page, int pagesize) {
        User user = UserHolder.getUser();

        IPage<UserInfo> iPage = blackListApi.findByUserId(page, pagesize, user.getId());
        PageResult vo = new PageResult();
        vo.setCounts((int) iPage.getTotal());
        vo.setPage(page);
        vo.setPages((int) iPage.getPages());
        vo.setPagesize(pagesize);
        vo.setItems(iPage.getRecords());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity removeBlackList(Long blackUserId) {
        User user = UserHolder.getUser();
        blackListApi.delete(user.getId(), blackUserId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity sendVerificationCode() {
        //1. 查询当前用户
        User user = UserHolder.getUser();
        //发送短信并获取
        String code = "123456";
        //3. 把验证码真实值存储到redis，有效期5分钟
        redisTemplate.opsForValue().set("CODE_" + user.getMobile(), code, Duration.ofMinutes(5));
        //4. 返回响应结果
        return ResponseEntity.ok(null);
    }

    public ResponseEntity checkVerificationCode(String verificationCode) {
        User user = UserHolder.getUser();
        String code = redisTemplate.opsForValue().get("CODE_" + user.getMobile());
        boolean valid = code != null && code.equals(verificationCode);
        if (valid) {
            redisTemplate.delete("CODE_" + user.getMobile());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("verification", valid);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity updateMobile(String newPhone) {
        User user = UserHolder.getUser();
        User newUser = new User();
        newUser.setMobile(newPhone);
        newUser.setId(user.getId());
        userApi.update(newUser);
        return null;
    }

    public ResponseEntity userLikeCounts() {
        Long userId = UserHolder.getUser().getId();
        Long likeCount = userLikeApi.queryLikeCount(userId);
        Long fansCount = userLikeApi.queryFansCount(userId);
        Long friendsCount = userLikeApi.queryFriendsCount(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("loveCount", likeCount);
        map.put("fanCount", fansCount);
        map.put("eachLoveCount", friendsCount);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity userLikeList(Integer type, int page, int pagesize) {
        Long userId = UserHolder.getUser().getId();
        PageResult pageResult = null;
        if (type == 1) {
            pageResult = userLikeApi.queryFriendsList(userId, page, pagesize);
        } else if (type == 2) {
            pageResult = userLikeApi.queryLikeList(userId, page, pagesize);
        } else if (type == 3) {
            pageResult = userLikeApi.queryFansList(userId, page, pagesize);
        } else if (type == 4) {

            pageResult = userLikeApi.findVisitorList(userId, page, pagesize);
        }
        List<CommonLikeUser> commonList = pageResult.getItems();
        List<CommonLikeUserVO> voList = new ArrayList<>();
        for (CommonLikeUser commonLikeUser : commonList) {
            CommonLikeUserVO vo = new CommonLikeUserVO();
           UserInfo userInfo= userInfoApi.findById(commonLikeUser.getTargetUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setMatchRate(commonLikeUser.getScore().intValue());
            voList.add(vo);
        }
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity likeFans(Long fansId) {
        Long userId = UserHolder.getUser().getId();
        //删除 粉丝对当前用户的喜欢
        userLikeApi.delete(fansId, userId);

        //添加两者好友关系
        friendApi.addFriend(userId,fansId);

        //在环信上注册好友关系
        huanXinTemplate.addContact(UserHolder.getUser().getId().toString(), fansId.toString());

        return ResponseEntity.ok(null);
    }

    public ResponseEntity delete(Long fansId) {
        Long userId = UserHolder.getUser().getId();
        userLikeApi.delete(userId, fansId);
        friendApi.deleteById(userId, fansId);

        return ResponseEntity.ok(null);
    }
}
